package com.aote.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.browsesoft.Entity;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLFormComponent;
import com.browsesoft.tools.BSCalendar;
import com.browsesoft.util.RequestHelper;

/**
 * 执行界面配置上的一批SQL语句
 */
public class BatchSQLQuery extends BatchSQLQueryBase {
	/**
	 * 对应的组件和请求
	 */
	private HTMLBasicComponent component;

	private HttpServletRequest request;

	public BatchSQLQuery(HTMLBasicComponent component,
			HttpServletRequest request) {
		this.component = component;
		this.request = request;
		this.setConfig(this.component.getElement());
	}

	/**
	 * 替换sql中的参数为父组件模型的属性值
	 */
	protected String replaceParams(String sql) {
		HTMLFormComponent comp = (HTMLFormComponent) ComponentHelper
				.getComponent(component, HTMLFormComponent.class);
		// 没有在form组件下，不替换
		if (comp == null) {
			return sql;
		}
		String result = RequestHelper.replaceParameter(request, sql);
		Entity entity = (Entity) comp.getModel();
		Map attrs = entity.getAttributes();
		result = StringHelper.replaceStr(attrs, result);
		// 替换统计意义上的月开始及结束
		result = replaceCalendar(result);
		return result;
	}

	/**
	 * 替换sql中统计意义上的开始天及结束天
	 */
	private String replaceCalendar(String sql) {
		// 替换月开始
		BSCalendar c = BSCalendar.startDayOfMonth();
		String str = c.toString("yyyymmdd");
		String result = sql.replaceAll("#MonthStartDay#", str);
		// 替换月结束
		c = BSCalendar.endDayOfMonth();
		str = c.toString("yyyymmdd");
		result = result.replaceAll("#MonthEndDay#", result);
		return result;
	}
}
